const express = require("express");
const { login } = require("./modules/login");
const { register } = require("./modules/register");
const getUser = require("./modules/getUser");
const session = require("express-session")
const multer = require("multer");
const _upload = require("./modules/upload");
const setUser = require("./modules/setUser");
const https = require("https");
const url = require("url")
const qs = require("querystring");

const app = express();

const upload = multer({ dest: "./upload" });
app.use(upload.any());

app.use(express.static("./www"));
app.use(express.static("./upload"));

app.use(express.urlencoded({extended: false}));

app.use(session({
    secret: '千锋H5',   // 加密信息，可以随便写
    resave: false,     // 强制保存session，默认为true，建议设置为false
    saveUninitialized: true,   // 强制将未初始化的session存储，默认为true，建议为true
    cookie: { maxAge: 1000 * 60 * 30 }    // 过期时间，毫秒数
}));

// 配置cors策略
app.all("*",(req,res,next)=>{
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Methods', 'get,post')
    res.header('Access-Control-Allow-Headers', 'Content-Type')
    next();
})

app.get("/login", login() );

app.post("/register", register("hello") );

app.get("/getUser", getUser() );

app.post("/upload", _upload() );

app.post("/setUser", setUser() );

// jsonp测试接口
app.get("/jsonp", (req,res,next)=>{
    // 从数据库中获取到一段数据...
    const data = "这是来自后端从数据库中获取到的数据";
    res.send(`
        const ahsj = "${data}";
    `);
} );

// jsonp接口
app.get("/getJsonp", (req,res,next)=>{
    // 从数据库中获取到一段数据...
    const obj = {
        code:1,
        msg:"请求成功，数据在data属性内",
        data: "这是来自后端从数据库中获取到的数据"
    }

    res.send(`
        ${req.query.cb}('${JSON.stringify(obj)}');
    `);
} );

// 网易云音乐xxx歌词的代理接口
app.get("/song/lyric", (req,res,next)=>{
    // 拼接处理要请求的真正的数据地址
    const urlObj = url.parse("https://music.163.com/weapi" + req.url)
    // 发起跨域请求
    const request = https.request({
        hostname: urlObj.hostname,
        port: 443,
        method: "post",
        path: urlObj.pathname,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    }, response=>{
        // 接收到跨域请求的响应
        // 解析数据
        let str = "";
        response.on("data",(chunk)=>{
            str += chunk
        })
        response.on("end",()=>{
            // 给客户端响应->接收到的跨域的数据
            res.send(str);
        })
    })
    // 发起跨域请求时携带的数据
    request.write(qs.stringify(req.query));
    // 结束本次跨域请求
    request.end();
} );

app.listen(3000, ()=>{
    console.log("服务器开启成功,地址为: http://localhost:3000")
})
